#include "driver_timer.h"
#include "stm32f401xc.h"
#include "tim.h"

void delay_us(int us)
{
#if 0
    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;
    uint32_t reload = SysTick->LOAD;

    ticks = us * 84;
    told = SysTick->VAL;
    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            if (tnow < told)
            {
                tcnt += told - tnow;
            }
            else
            {
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if (tcnt >= ticks)
            {
                break;
            }
        }
    }
#else
    extern TIM_HandleTypeDef        htim2;
    TIM_HandleTypeDef *hHalTim = &htim2;

    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;
    uint32_t reload = __HAL_TIM_GET_AUTORELOAD(hHalTim);

    // ticks = us * (定时器计数频率) / 1000000 = us * 定时器时钟频率 / 预分频
    ticks = us;  /* 假设reload对应1ms */
    told = __HAL_TIM_GET_COUNTER(hHalTim);
    while (1)
    {
        tnow = __HAL_TIM_GET_COUNTER(hHalTim);
        if (tnow != told)
        {
            if (tnow > told)
            {
                tcnt += tnow - told;
            }
            else
            {
                tcnt += reload - told + tnow;
            }
            told = tnow;
            if (tcnt >= ticks)
            {
                break;
            }
        }
    }
#endif
}

void delay_ms(int ms)
{
    for (int i = 0; i < ms; i++)
        delay_us(1000);
}

 uint64_t system_get_ns(void)
 {
     //extern uint32_t HAL_GetTick(void);
     extern TIM_HandleTypeDef        htim2;
     TIM_HandleTypeDef *hHalTim = &htim2;

     uint64_t ns = HAL_GetTick();
     uint64_t cnt;
     uint64_t reload;

     cnt = __HAL_TIM_GET_COUNTER(hHalTim);
     reload = __HAL_TIM_GET_AUTORELOAD(hHalTim);

     ns *= 1000000;
     ns += cnt * 1000000 / reload;
     return ns;
 }

 unsigned long getRunTimeCounterValue(void)
 {
      return system_get_ns() / 1000;
 }
